<template>
  <!-- 搜索条件 -->
  <el-card class="top">
    <el-form class="search-form">
      <div class="top-left">
        <!-- 用户名 -->
        <el-form-item label="角色名称：" prop="roleName">
          <el-input
              v-model="searchDataForm.roleName"
              clearable
              :prefix-icon="Avatar"
              placeholder="请你输入搜索角色名称"
          />
        </el-form-item>
        <!-- 昵称 -->
        <el-form-item label="角色编码：" prop="roleCode">
          <el-input
              v-model="searchDataForm.roleCode"
              clearable
              :prefix-icon="Setting"
              placeholder="请你输入搜索角色编码"
          />
        </el-form-item>
      </div>
      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="searchForm">
          搜索
        </el-button>
        <el-button @click="resetForm">
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 展示数据 -->
  <el-card class="bottom">
    <!-- 按钮 -->
    <el-button type="primary" @click="addRole">添加</el-button>
    <el-popconfirm title="你确定要批量删除吗？" width="260px"
                   @confirm="deleteSelectUser"
    >
      <template #reference>
        <el-button type="danger" size="default"
                   :disabled="!selectIdArr.length"
        >
          批量删除
        </el-button>
      </template>
    </el-popconfirm>
    <!-- 表格展示用户信息 -->
    <el-table style="width: 100%" height="50vh"
              class="bottom-table"
              :header-cell-style="{'text-align':'center'}"
              :cell-style="{'text-align':'center'}"
              :data="records"
              border
              @selection-change="selectChange"
    >
      <!-- 多选框 -->
      <el-table-column fixed="left" type="selection" width="50"/>
      <!-- 序号 -->
      <el-table-column fixed="left" type="index" label="#" width="50"/>
      <!-- 角色名称 -->
      <el-table-column sortable
                       prop="roleName"
                       label="角色名称"
                       width="200"
                       show-overflow-tooltip
      />
      <!-- 角色编码 -->
      <el-table-column sortable
                       prop="roleCode"
                       label="角色编码"
                       width="200"
                       show-overflow-tooltip
      />
      <!-- 创建时间 -->
      <el-table-column sortable
                       prop="createTime"
                       label="创建时间"
                       show-overflow-tooltip
                       width="200"
      />
      <!-- 更新时间 -->
      <el-table-column sortable
                       prop="updateTime"
                       label="更新时间"
                       show-overflow-tooltip
                       width="200"
      />
      <!-- 创建者 -->
      <el-table-column sortable
                       prop="createUser"
                       label="创建者"
                       show-overflow-tooltip
                       width="200"
      />
      <!-- 更新者 -->
      <el-table-column sortable
                       prop="updateUser"
                       label="更新者"
                       show-overflow-tooltip
                       width="200"
      />
      <!-- 操作 -->
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="props">
          <el-button type="primary"
                     icon="Edit"
                     size="small"
                     @click="updateRole(props.row)"
          >
            编辑
          </el-button>
          <el-popconfirm :title="`你确定要删除${props.row.name}?`" width="260px"
                         @confirm="deleteRole(props.row.id)"
          >
            <template #reference>
              <el-button type="danger"
                         size="small"
                         icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination v-model:current-page="pageNumber"
                   v-model:page-size="pageSize"
                   :page-sizes="[5, 10, 15, 20]"
                   :background="true"
                   layout="prev, pager, next, jumper,->,sizes,total"
                   :total="totalRow"
                   @current-change="searchForm"
                   @size-change="searchForm"
    />
  </el-card>

  <!-- 添加或者更新权限的对话框 -->
  <el-dialog v-model="drawer">
    <!-- 头部标题:将来文字内容应该动态的 -->
    <template #header>
      <h4>{{ roleParams.id ? '修改权限' : '添加权限' }}</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form :model="roleParams"
               :rules="rules"
               ref="ruleFormRef"
               :inline="true"
               label-position="top"
               class="dialog-add-or-update-form"
      >
        <!-- 角色名称 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input placeholder="请您输入角色名称"
                    v-model="roleParams.roleName"
                    maxlength="20"
                    show-word-limit
                    clearable
          />
        </el-form-item>
        <!-- 角色编码 -->
        <el-form-item label="角色编码" prop="roleCode">
          <el-input placeholder="请您输入角色编码"
                    v-model="roleParams.roleCode"
                    maxlength="20"
                    show-word-limit
                    clearable
          />
        </el-form-item>
        <!-- 角色描述 -->
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input placeholder="请您输入角色描述"
                    type="textarea"
                    v-model="roleParams.roleDesc"
                    maxlength="255"
                    show-word-limit
                    clearable
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button type="primary" @click="save(ruleFormRef)">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">

import {Avatar, Setting} from "@element-plus/icons-vue";
import {onMounted, reactive, ref, nextTick} from "vue";
import {addRoleReq, deleteRoleByIdReq, deleteRoleByIdsReq, pageRoles, Records, updateRoleReq} from "@/api/role/role.ts";
import {FormInstance, FormRules} from "element-plus";

interface SearchData {
  roleName: string,
  roleCode: string
}

// 搜索条件
const searchDataForm = reactive<SearchData>({
  roleName: '',
  roleCode: ''
})

// 收集权限信息的响应式数据
let roleParams = reactive({
  id: '',
  createTime: '',
  updateTime: '',
  createUser: '',
  updateUser: '',
  roleName: '',
  roleCode: '',
  roleDesc: ''
});

// 默认页码
const pageNumber = ref<number>(1);
// 默认每页条数
const pageSize = ref<number>(10);
// 总条数
const totalRow = ref<number>(0);
// 存储表格数据
const records = ref<Records[]>([]);
//准备一个数组存储批量删除的用户的ID
const selectIdArr = ref<Records[]>([]);
// 定义响应式数据控制抽屉的显示与隐藏
const drawer = ref<boolean>(false);
// 校验表单的ref
const ruleFormRef = ref<FormInstance>()

//表单校验的规则对象
const rules = reactive<FormRules>({
  // 权限名字
  roleName: [{required: true, trigger: 'blur', message: "请输入角色名称"}],
  // 权限编码
  roleCode: [{required: true, trigger: 'blur', message: "请输入角色编码"}],
})

// 搜索表单
const searchForm = async () => {
  const data = {
    roleName: searchDataForm.roleName,
    roleCode: searchDataForm.roleCode,
    pageNum: pageNumber.value,
    pageSize: pageSize.value
  }
  const result: any = await pageRoles(data)
  if (result.code === 1000_0000) {
    totalRow.value = result.data.totalRow
    records.value = result.data.records
  }
}

// 重置表单
const resetForm = () => {
  searchDataForm.roleName = ''
  searchDataForm.roleCode = ''
}

// 数据初始化
onMounted(() => {
  pageRole()
})

// 分页查询用户
const pageRole = async () => {
  const data = {
    pageNum: pageNumber.value,
    pageSize: pageSize.value
  }
  const result: any = await pageRoles(data)
  if (result.code === 1000_0000) {
    totalRow.value = result.data.totalRow
    records.value = result.data.records
  }
}

// 添加按钮
const addRole = () => {
  drawer.value = true
  //清空数据
  Object.assign(roleParams, {
    id: '',
    createTime: '',
    updateTime: '',
    createUser: '',
    updateUser: '',
    roleName: '',
    roleCode: '',
    roleDesc: ''
  });
  //清除上一次的错误的提示信息
  nextTick(() => {
    ruleFormRef.value?.clearValidate('roleName');
    ruleFormRef.value?.clearValidate('roleCode');
  });
}

// 修改按钮
const updateRole = (row: Records) => {
  drawer.value = true
  //清除上一次的错误的提示信息
  nextTick(() => {
    ruleFormRef.value?.clearValidate('roleName');
    ruleFormRef.value?.clearValidate('roleCode');
  });
  // ES6语法合并对象
  Object.assign(roleParams, row);
}

//保存按钮的回调
const save = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (!valid) {
      console.log('校验失败!', fields)
      return
    }
    // 保存按钮:添加新的用户|更新已有的用户账号信息
    const result: any = roleParams.id ? await updateRoleReq(roleParams) : await addRoleReq(roleParams)
    //添加或者更新成功
    if (result.code == 1000_0000) {
      //关闭抽屉
      drawer.value = false;
      //提示消息
      ElMessage({type: 'success', message: roleParams.id ? '更新成功' : '添加成功'});
      //获取最新的全部账号的信息
      //浏览器自动刷新一次
      await pageRole()
    }
  })
}

// table复选框勾选的时候会触发的事件
const selectChange = (value: any) => {
  selectIdArr.value = value;
}

// 取消按钮的回调
const cancel = () => {
  //关闭抽屉
  drawer.value = false;
}

// 删除某一个用户
const deleteRole = async (userId: string) => {
  let result: any = await deleteRoleByIdReq(userId);
  if (result.code === 1000_0000) {
    ElMessage({type: 'success', message: '删除成功'});
    //浏览器自动刷新一次
    await pageRole()
  }
}

// 批量删除按钮的回调
const deleteSelectUser = async () => {
  //整理批量删除的参数
  let ids: any = selectIdArr.value.map(item => item.id);
  //批量删除的请求
  let result: any = await deleteRoleByIdsReq(ids);
  if (result.code === 1000_0000) {
    ElMessage({type: 'success', message: '删除成功'});
    //浏览器自动刷新一次
    await pageRole()
  }
}

</script>

<style scoped lang="scss">
.top {
  margin-bottom: 2vh;

  .top-left {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 50%;
  }

  .search-form {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-form-item {
      margin-bottom: 0;

      .el-input {
        width: 220px;
      }
    }
  }
}

.bottom {

  .bottom-table {
    margin: 2vh 0;
  }
}

.dialog-add-or-update-form {
  width: 100%;
  display: flex;
  justify-content: space-between;

  .el-form-item {
    width: 45%;
  }
}
</style>
